<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Demo</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
    <div>
        <label>用户ID：</label>
        <input type="text" id="userId" value="user123" />
    </div>
    <div>
        <label>接收者ID：</label>
        <input type="text" id="receiverId" />
    </div>
    <div>
        <label>消息内容：</label>
        <input type="text" id="content" />
        <button onclick="sendMessage()">发送</button>
    </div>
    <div id="messages"></div>

    <script>
        var socket = new SockJS('/websocket');
        var stompClient = Stomp.over(socket);
        
        // 添加用户ID到连接头信息
        var userId = document.getElementById('userId').value;
        var headers = {
            userId: userId
        };
        
        stompClient.connect(headers, function(frame) {
            console.log('Connected: ' + frame);
            
            // 订阅广播消息
            stompClient.subscribe('/topic/broadcast', function(response) {
                var message = JSON.parse(response.body);
                appendMessage('收到广播消息: ' + formatMessage(message));
            });
            
            // 订阅个人消息
            stompClient.subscribe('/queue/message/' + userId, function(response) {
                var message = JSON.parse(response.body);
                appendMessage('收到个人消息: ' + formatMessage(message));
            });
        });

        function sendMessage() {
            var userId = document.getElementById('userId').value;
            var receiverId = document.getElementById('receiverId').value;
            var content = document.getElementById('content').value;

            var message = {
                from: userId,
                to: receiverId || 'all',
                content: content,
                timestamp: new Date().getTime()
            };

            // 如果没有指定接收者，则广播消息
            if (!receiverId) {
                stompClient.send("/app/broadcast", {}, JSON.stringify(message));
            }
            
            document.getElementById('content').value = '';
        }

        function formatMessage(message) {
            return `从 ${message.from || 'system'} 到 ${message.to}: ${message.content} (${new Date(message.timestamp).toLocaleString()})`;
        }

        function appendMessage(message) {
            var messageDiv = document.getElementById('messages');
            messageDiv.innerHTML = '<div>' + message + '</div>' + messageDiv.innerHTML;
        }
    </script>
</body>
</html> 